from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.generics import GenericAPIView
from news.models import News, NewsCategory
from rest_framework.response import Response
from news.serializers import Newstop, SNewsCategory


# Create your views here.

# GET /news/top/

class NewsTop(GenericAPIView):
    serializer_class = Newstop

    def get(self, request):
        '''获取界面顶部新闻, 轮播新闻, 推荐新闻, 图片新闻'''
        # 1. 获取新闻数据

        # 2. 返回响应

        news = News.objects.filter(is_slide=True).all()
        serializer = self.get_serializer(news, many=True)

        top_news = News.objects.order_by('-create_time')[:10]
        top_serializer = self.get_serializer(top_news, many=True)

        im_news = News.objects.exclude(img_url='').order_by('-click')[:4]
        image_news_serializer = self.get_serializer(im_news, many=True)

        # {
        #     'slide_news': [{第1条新闻}, {第2条新闻}, ...],
        #     'top_news': [{第1条新闻}, {第2条新闻}, ...],
        #     'image_news': [{第1条新闻}, {第2条新闻}, ...]
        # }

        data = {
            'slide_news': serializer.data,
            'top_news': top_serializer.data,
            'image_news': image_news_serializer.data

        }

        return Response(data)


# URL: /news/category/
# 类别新闻
class CategoryNews(APIView):
    def get(self, request):
        '''获取类别新闻'''
        resp = []
        parent_news = NewsCategory.objects.filter(parent_id=0)


        for son_news in parent_news:
            category_news = NewsCategory.objects.filter(parent_id=son_news.id)
            #
            category = []
            seralizer = SNewsCategory(category_news, many=True)

            category.append(seralizer.data)

            son=[]
            # i=0
            for tamp in category_news:
                # print(tamp.id)
                son.append(tamp.id)
                news = News.objects.filter(category_id__in=son).exclude(img_url='').order_by('-create_time')[:4]
                news_top8 = News.objects.filter(category_id__in=son).order_by('-click')[:8]

                newstop = Newstop(news, many=True)
                news_top8 = Newstop(news_top8, many=True)
                # print(tamp.id, '==========', newstop.data)
                # i += 1
                # print(i,'...........')

                res = {
                    "id": son_news.id,
                    "newscategory_set": category,
                    "create_time": son_news.create_time,
                    "update_time": son_news.update_time,
                    "title": son_news.title,
                    "sort_id": son_news.sort_id,
                    "news": newstop.data,
                    'top8':news_top8.data,
                }

            resp.append(res)
        return Response(resp)
